<!-- templates/speech.html -->
<!DOCTYPE html>
<html>
<head>
    <title>花艺AI - 语音交互</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; padding-top: 2rem; }
        .header { margin-bottom: 2rem; }
        .container { max-width: 800px; margin: 0 auto; }
        .control-panel { display: flex; margin-bottom: 20px; flex-wrap: wrap; }
        .col { flex: 1; padding: 10px; min-width: 300px; }
        button { padding: 10px; margin: 5px; cursor: pointer; }
        .recording { color: red; }
        select, input { padding: 8px; margin: 5px 0; width: 100%; }
        #result { margin-top: 20px; padding: 15px; border: 1px solid #ddd; background-color: #f9f9f9; }
        .response-container { margin-top: 20px; }
        .image-container { margin-top: 15px; }
        .image-container img { max-width: 100%; }
        .audio-container { margin-top: 15px; }
        #status-indicator { padding: 5px 10px; border-radius: 3px; display: inline-block; }
        .dialect-result { margin-top: 10px; font-weight: bold; }
        .available { background-color: #28a745; color: white; }
        .unavailable { background-color: #dc3545; color: white; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header text-center">
            <h1>花艺AI测试应用</h1>
            <p class="lead">语音交互</p>
            <nav class="nav justify-content-center">
                <a class="nav-link" href="/">首页</a>
                <a class="nav-link" href="/upload">上传知识</a>
                <a class="nav-link" href="/image">生成图像</a>
                <a class="nav-link" href="/speech">语音交互</a>
                <a class="nav-link" href="/video/list">视频库</a>
                <a class="nav-link" href="/status">系统状态</a>
            </nav>
        </div>

        <div class="card">
            <div class="card-header bg-success text-white">
                <h3>语音与花艺AI系统交互</h3>
                <p class="mb-0">支持多种方言，说出您的花艺问题</p>
            </div>

            <div class="card-body">
                <div class="control-panel">
                    <div class="col">
                        <h4>语音设置</h4>
                        <label for="dialect">选择方言:</label>
                        <select id="dialect" class="form-select">
                            <option value="mandarin">普通话</option>
                            <option value="cantonese">粤语</option>
                            <option value="sichuan">川渝话</option>
                            <option value="auto">自动检测</option>
                        </select>

                        <label for="voice-id">语音合成声音:</label>
                        <select id="voice-id" class="form-select">
                            <option value="">默认声音</option>
                            {% for group, voice_list in voices.items() %}
                                <optgroup label="{{ group }}">
                                    {% for voice in voice_list %}
                                        <option value="{{ voice }}">{{ voice }}</option>
                                    {% endfor %}
                                </optgroup>
                            {% endfor %}
                        </select>

                        <label for="speed">语音速度:</label>
                        <div class="d-flex align-items-center">
                            <input type="range" id="speed" class="form-range" min="0.5" max="2" step="0.1" value="1">
                            <span id="speed-value" class="ms-2">1.0</span>
                        </div>
                    </div>

                    <div class="col">
                        <h4>查询选项</h4>
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="generate-image" checked>
                            <label class="form-check-label" for="generate-image">生成图像</label>
                        </div>

                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="voice-response" checked>
                            <label class="form-check-label" for="voice-response">语音回答</label>
                        </div>

                        <div id="status">
                            <h4>系统状态:</h4>
                            <div>ASR可用:
                                <span id="status-indicator" class="{{ 'available' if status.speech_interaction.asr_available.deepseek_asr else 'unavailable' }}">
                                    {{ '可用' if status.speech_interaction.asr_available.whisper or status.speech_interaction.asr_available.deepseek_asr else '不可用' }}
                                </span>
                            </div>
                            <div>TTS可用:
                                <span id="status-indicator" class="{{ 'available' if status.speech_interaction.tts_available.vits2 or status.speech_interaction.tts_available.edge_tts else 'unavailable' }}">
                                    {{ '可用' if status.speech_interaction.tts_available.vits2 or status.speech_interaction.tts_available.edge_tts else '不可用' }}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="text-center mb-4">
                    <button id="start-recording" class="btn btn-primary">开始录音</button>
                    <button id="stop-recording" class="btn btn-danger" disabled>停止录音</button>
                    <button id="detect-dialect" class="btn btn-info">检测方言</button>
                    <span id="recording-status" class="ms-3"></span>
                </div>

                <div class="dialect-result alert alert-info d-none" id="dialect-result"></div>

                <div id="result" class="card">
                    <div class="card-header">查询结果</div>
                    <div class="card-body">
                        <div id="transcription" class="mb-4"></div>
                        <div class="response-container">
                            <div id="text-response"></div>
                            <div class="image-container mt-4" id="image-container"></div>
                            <div class="audio-container mt-4" id="audio-container"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 录音相关变量
        let mediaRecorder;
        let audioChunks = [];
        let recording = false;

        // 页面元素
        const startButton = document.getElementById('start-recording');
        const stopButton = document.getElementById('stop-recording');
        const detectDialectButton = document.getElementById('detect-dialect');
        const recordingStatus = document.getElementById('recording-status');
        const dialectSelect = document.getElementById('dialect');
        const voiceIdSelect = document.getElementById('voice-id');
        const speedSlider = document.getElementById('speed');
        const speedValue = document.getElementById('speed-value');
        const generateImageCheckbox = document.getElementById('generate-image');
        const voiceResponseCheckbox = document.getElementById('voice-response');
        const transcriptionDiv = document.getElementById('transcription');
        const textResponseDiv = document.getElementById('text-response');
        const imageContainerDiv = document.getElementById('image-container');
        const audioContainerDiv = document.getElementById('audio-container');
        const dialectResultDiv = document.getElementById('dialect-result');

        // 语音速度滑块事件
        speedSlider.addEventListener('input', function() {
            speedValue.textContent = this.value;
        });

        // 开始录音
        startButton.addEventListener('click', async () => {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                mediaRecorder = new MediaRecorder(stream);
                audioChunks = [];

                mediaRecorder.addEventListener('dataavailable', event => {
                    audioChunks.push(event.data);
                });

                mediaRecorder.addEventListener('stop', () => {
                    recording = false;
                    recordingStatus.textContent = '';
                    startButton.disabled = false;
                    stopButton.disabled = true;

                    // 处理录制的音频
                    processAudio();
                });

                mediaRecorder.start();
                recording = true;
                recordingStatus.textContent = '正在录音...';
                recordingStatus.className = 'recording';
                startButton.disabled = true;
                stopButton.disabled = false;
            } catch (err) {
                console.error('录音初始化失败:', err);
                alert('无法访问麦克风，请确保已授权浏览器使用麦克风。');
            }
        });

        // 停止录音
        stopButton.addEventListener('click', () => {
            if (mediaRecorder && recording) {
                mediaRecorder.stop();
            }
        });

        // 检测方言
        detectDialectButton.addEventListener('click', async () => {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                mediaRecorder = new MediaRecorder(stream);
                audioChunks = [];

                mediaRecorder.addEventListener('dataavailable', event => {
                    audioChunks.push(event.data);
                });

                mediaRecorder.addEventListener('stop', () => {
                    recording = false;
                    recordingStatus.textContent = '';
                    detectDialectButton.disabled = false;

                    // 处理录制的音频进行方言检测
                    detectDialect();
                });

                mediaRecorder.start();
                recording = true;
                recordingStatus.textContent = '录音中 (3秒)...';
                recordingStatus.className = 'recording';
                detectDialectButton.disabled = true;

                // 3秒后自动停止录音
                setTimeout(() => {
                    if (mediaRecorder && recording) {
                        mediaRecorder.stop();
                    }
                }, 3000);
            } catch (err) {
                console.error('录音初始化失败:', err);
                alert('无法访问麦克风，请确保已授权浏览器使用麦克风。');
            }
        });

        // 处理录音数据，发送到服务器
        async function processAudio() {
            const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
            const formData = new FormData();
            formData.append('audio', audioBlob);
            formData.append('dialect', dialectSelect.value);
            formData.append('generate_image', generateImageCheckbox.checked);
            formData.append('voice_response', voiceResponseCheckbox.checked);
            formData.append('voice_id', voiceIdSelect.value);

            try {
                transcriptionDiv.textContent = '处理中...';
                textResponseDiv.textContent = '';
                imageContainerDiv.innerHTML = '';
                audioContainerDiv.innerHTML = '';

                const response = await fetch('/speech-query', {
                    method: 'POST',
                    body: formData
                });

                if (response.ok) {
                    const result = await response.json();

                    // 显示转写文本
                    transcriptionDiv.innerHTML = `<strong>您说:</strong> ${result.transcription || '无法识别'}`;

                    // 显示文本回复
                    textResponseDiv.innerHTML = `<strong>回答:</strong><br>${result.response || ''}`;

                    // 显示图像（如果有）
                    if (result.image_url) {
                        imageContainerDiv.innerHTML = `
                            <h4>生成的图像:</h4>
                            <img src="${result.image_url}" alt="生成的花艺图像" class="img-fluid">
                        `;
                    }

                    // 播放语音回答（如果有）
                    if (result.audio_response) {
                        const audio = new Audio(`data:audio/wav;base64,${result.audio_response}`);
                        audioContainerDiv.innerHTML = `<h4>语音回答:</h4>`;

                        const audioElement = document.createElement('audio');
                        audioElement.controls = true;
                        audioElement.src = `data:audio/wav;base64,${result.audio_response}`;
                        audioContainerDiv.appendChild(audioElement);

                        if (voiceResponseCheckbox.checked) {
                            audio.play();
                        }
                    }
                } else {
                    const errorData = await response.json();
                    transcriptionDiv.textContent = `错误: ${errorData.error || '处理请求时出错'}`;
                }
            } catch (err) {
                console.error('处理音频时出错:', err);
                transcriptionDiv.textContent = `错误: ${err.message || '无法处理录音'}`;
            }
        }

        // 检测方言
        async function detectDialect() {
            const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
            const formData = new FormData();
            formData.append('audio', audioBlob);

            try {
                dialectResultDiv.textContent = '正在检测方言...';
                dialectResultDiv.classList.remove('d-none');

                const response = await fetch('/detect-dialect', {
                    method: 'POST',
                    body: formData
                });

                if (response.ok) {
                    const result = await response.json();
                    const dialects = result.dialects || [];

                    if (dialects.length > 0) {
                        // 显示检测结果
                        const topDialect = dialects[0];
                        dialectResultDiv.textContent = `检测到的方言: ${getDialectName(topDialect.dialect)} (置信度: ${(topDialect.confidence * 100).toFixed(1)}%)`;

                        // 自动设置方言选择器
                        dialectSelect.value = topDialect.dialect;
                    } else {
                        dialectResultDiv.textContent = '无法检测方言';
                    }
                } else {
                    const errorData = await response.json();
                    dialectResultDiv.textContent = `错误: ${errorData.error || '方言检测失败'}`;
                }
            } catch (err) {
                console.error('检测方言时出错:', err);
                dialectResultDiv.textContent = `错误: ${err.message || '方言检测失败'}`;
            }
        }

        // 方言名称映射
        function getDialectName(dialect) {
            const dialectNames = {
                'mandarin': '普通话',
                'cantonese': '粤语',
                'sichuan': '川渝话',
                'standard': '标准中文'
            };
            return dialectNames[dialect] || dialect;
        }
    </script>
</body>
</html>